import * as React from 'react'
import { Button, makeStyles, createStyles, Grid, experimentalStyled } from '@material-ui/core'
import { debounce, throttle } from 'underscore'
import { Layout } from 'antd'

// import { delay } from '../../utils/time'
import post from '../../utils/web';
import { Showindex } from '../types';
import Setupindex from './setupInde'
import { ipcRenderer } from 'electron'
import { ipctype } from '../../main/interface';
import i56 from '../../assets/l-56.png'

type Props = {
  setIndex(name: Showindex): void,
  fullscreen(): void
}

const { Content, Footer, Header, Sider } = Layout


const useStyles = makeStyles(() => createStyles({
  root: {
    flexGrow: 1,
  },
  headertop: {
    height: '100px',
    display: 'flex',
    position: 'relative',
    alignItems: 'center'
  },
  headerbut2: {
    fontSize: '55px',
    marginLeft: '0.7rem',
    marginRight: '0.7rem',
    backgroundColor: '#0072FF',
    '&:hover': {
      backgroundColor: '#0072FF',
    },
  },
  main: {
    display: 'flex',
    position: 'relative',
    width: '1000px',
    height: '487px',
    margin: '0 auto',
    textAlign: 'center',
  },
  footer: {
    width: '100vw',
    overflow: 'hidden',
    marginTop: '5px'
  },
  headerbut3: {
    fontSize: '55px',
    backgroundColor: '#FEBF32 !important',
    '&:hover': {
      backgroundColor: '#0072FF !important',
    },
  },
  headerStepper: {
    height: '67px',
    borderRadius: '6px',
  },
  Stepper1: {
    marginTop: '4px'
  },
  setmain: {
    width: '921px',
    height: '487px',
    borderRadius: '25px',
    margin: '0 auto',
    border: '2px solid #ffffff'
  },
  hdiv: {
    textAlign: 'left',
    fontWeight: 'bold',
    color: '#070A17',
    fontSize: '27px',
    paddingLeft: '25px',
    paddingTop: '16px',
    paddingBottom: '5px',
  },
  div1: {
    textAlign: 'right',
    lineHeight: '400px',
    marginRight: '-20px',
    zIndex: 30
  },
  imagestyle: {
  },
  mybutton: {
    width: '215px',
    height: '48px',
    backgroundColor: '#0072ff',
    borderRadius: '17px !important',
    fontSize: '24px',
    fontWeight: 'bold',
    marginLeft: '50px !important',
    marginRight: '10px !important'
  },
}));


const I56button = experimentalStyled(Button)({
  backgroundImage: `url(${i56})`,
  backgroundSize: 'cover',
  backgroundRepeat: 'no-repeat'

})


const Rightbutton = experimentalStyled(I56button)({
  height: '48px',
  width: '245px',
  borderRadius: '17px',
  fontSize: '24px',
  fontWeight: 'bold',
})


const Mybutton = experimentalStyled(I56button)({
  width: '215px',
  height: '48px',
  borderRadius: '17px',
  fontSize: '24px',
  fontWeight: 'bold',
  marginLeft: '50px',
  marginRight: '10px',
})


const Iconbutton = experimentalStyled(Button)({
  width: '64px',
  height: '64px',
  fontSize: '64px',
  fontWeight: 'bold',
  color: '#ffffff',
  lineHeight: '64px',
  border: '2px solid #ffffff'

})


const Sideri = experimentalStyled(Sider)({
  height: '100px',
  backgroundColor: 'unset',
  textAlign: 'center',
  lineHeight: '100px',
})


const name = [
  { name: '拇指', number: 90, max: 99, min: 99 },
  { name: '食指', number: 90, max: 99, min: 99 },
  { name: '中指', number: 90, max: 99, min: 99 },
  { name: '无名指', number: 90, max: 99, min: 99 },
  { name: '小指', number: 90, max: 99, min: 99 },
  { name: '手腕', number: 90, max: 99, min: 99 },
  { name: '拇指关节', number: 90, max: 99, min: 99 },
]


export default function Setup(prop: Props) {
  const { setIndex } = prop
  const { setmain, footer } = useStyles();
  const [range, setranges] = React.useState(name)
  React.useEffect(() => {
    ipcRenderer.addListener(ipctype['arduino'], (_event, data) => {
      console.log(data.toString())
      read(data)
    })
    return () => {
      ipcRenderer.removeListener(ipctype['arduino'], (...arg) => {
        console.log(arg)
      })
    }
  }, [])

  function _setrange(index: number, value: number) {
    if (range[index]) {
      const data = Array.from(range)
      data[index].number = value
      setranges(data)
      const d = data.map(v => Math.floor(v.number / 1.8)).join(',').concat(',w')
      post(d)
    }
  }

  const setrange = debounce(_setrange, 50)

  /**
   * 设置arduino舵机量程
   * @param m {boolean}
   */
  function srange(m: boolean) {
    let str = range.map(v => v.number).join(',')
    if (m) {
      // 最大
      str = str.concat(',x\r\n')
    } else {
      // 最小
      str = str.concat(',y\r\n')
    }
    post(str)
  }


  /**
   * 写入本地最大最小
   * @param m 
   */
  function wrange(m: boolean) {
    let str = ''
    if (m) {
      // 最大
      str = range.map(v => Math.floor(v.max / 1.8)).join(',')
    } else {
      // 最小
      str = range.map(v => Math.floor(v.min / 1.8)).join(',')
    }
    const data = range.map(v => {
      const { min, max } = v
      if (m) {
        return Object.assign(v, {
          number: max
        })
      } else {
        return Object.assign(v, {
          number: min
        })
      }
    })
    setranges(data)
    str = str.concat(',w\r\n')
    post(str)
  }

  /**
   * 读取arduino舵机量程
   */
  function readrange() {
    let str = range.map(v => v.number).join(',').concat(',r\r\n')
    post(str, str).then((d) => {
      if (d) {
        const data = d.data
        read(data)
      }
    })
  }

  const readthrottle = throttle(readrange, 500)


  function read(data: Buffer) {
    const ascil = data.toString('ascii')
    const str = ascil.indexOf('read')
    if (str !== -1) {
      console.log(ascil)
      const tmp = ascil.replace(new RegExp(/[\r\n]/, 'g'), '')
      const str = tmp.indexOf('read')
      const arr = tmp.slice(str + 4).split(',')
      console.log(arr)
      const d = range.map((v, key) => {
        return Object.assign(v, {
          max: Number(arr[key]),
          min: Number(arr[key + range.length])
        })
      })
      setranges(d)
    }
  }

  return <>
    <Header style={{ backgroundImage: 'none' }} >
      <Layout style={{ lineHeight: '100px' }}>
        <Sideri width="100" >
          <Iconbutton onClickCapture={(e) => { e.stopPropagation(); setIndex('index') }}>
            <svg className="icon" aria-hidden="true">
              <use xlinkHref="#iconhome"></use>
            </svg>
          </Iconbutton>
        </Sideri>
        <Content>
          <Mybutton variant="contained" size="large" onClickCapture={() => srange(false)}>保存握拳角度</Mybutton>
          <Mybutton variant="contained" size="large" onClickCapture={() => srange(true)}>保存张开角度</Mybutton>
        </Content>
      </Layout>
    </Header>

    <Content >
      <div className={setmain}>
        {
          [Object.assign(range[2], { mykey: 2 }), Object.assign(range[1], { mykey: 1 }), Object.assign(range[3], { mykey: 3 }), Object.assign(range[4], { mykey: 4 }), Object.assign(range[0], { mykey: 0 }), Object.assign(range[6], { mykey: 6 }), Object.assign(range[5], { mykey: 5 })].map((v, key) => {
            return (<Setupindex name={v.name} key={key} max={v.max} min={v.min} mykey={v.mykey} index={v.number} setrange={setrange} wrange={wrange}  ></Setupindex>)
          })
        }
      </div>
    </Content>
    <Footer className={footer}>
      <Grid container spacing={2}>
        <Grid item xs={5} >
          <Rightbutton variant="contained" size="large" onClick={() => readthrottle()}>读取已保存的角度</Rightbutton>
        </Grid>
        <Grid item xs={3}>

        </Grid>
        <Grid item xs className="text-center">
          <I56button variant="contained" size="medium" onClick={() => wrange(false)}>握拳</I56button>
            &nbsp;&nbsp;
            <I56button variant="contained" size="medium" onClick={() => wrange(true)}>张开</I56button>
        </Grid>
      </Grid>
    </Footer>
  </>
}
